package com.lzb.musicplayer.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.view.View;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lzb.basic.utils.TimeUtil;
import com.lzb.musicplayer.BaseAc;
import com.lzb.musicplayer.BasePlayerActivity;
import com.lzb.musicplayer.Content;
import com.lzb.musicplayer.HomeActivity;
import com.lzb.musicplayer.R;
import com.lzb.musicplayer.adapter.MusicAdapter;
import com.lzb.musicplayer.bean.GroupMusicInfo;
import com.lzb.musicplayer.bean.MusicFile;
import com.lzb.musicplayer.bean.PlayListBean;
import com.lzb.musicplayer.databinding.ActivityPlaylistDetailBinding;
import com.lzb.musicplayer.dialog.DeleteDialog;
import com.lzb.musicplayer.dialog.InfoEditDialog;
import com.lzb.musicplayer.dialog.MusicEditDialog;
import com.lzb.musicplayer.dialog.PlaylistDialog;
import com.lzb.musicplayer.dialog.PlaylistEditDialog;
import com.lzb.musicplayer.dialog.RenamePlaylistDialog;
import com.lzb.musicplayer.utils.AppSpUtils;
import com.lzb.musicplayer.utils.MusicScanner;
import com.lzb.musicplayer.utils.MusicScannerUtil;
import com.lzb.musicplayer.utils.RingtoneUtil;
import com.lzb.musicplayer.utils.SaveListUtils;

import java.util.ArrayList;
import java.util.List;

public class PlaylistDetailActivity extends BasePlayerActivity<ActivityPlaylistDetailBinding> implements View.OnClickListener, OnItemClickListener, OnItemChildClickListener {

    public static int selPosition;
    private MusicAdapter musicAdapter;
    private PlayListBean playListBean;
    private List<GroupMusicInfo> listShow = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.activity_playlist_detail;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPlaylistDetailBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivEdit.setOnClickListener(this);
        mDataBinding.llPlay.setOnClickListener(this);
        mDataBinding.llRandomPlay.setOnClickListener(this);

        mDataBinding.rvMusicList.setLayoutManager(new LinearLayoutManager(mContext));
        musicAdapter = new MusicAdapter();
        mDataBinding.rvMusicList.setAdapter(musicAdapter);
        musicAdapter.addChildClickViewIds(R.id.ivMusicItemEdit);
        musicAdapter.setOnItemClickListener(this);
        musicAdapter.setOnItemChildClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivEdit) {//编辑
            showPlaylistEditDialog(playListBean.getMusicFileList());
        } else if (id == R.id.llPlay) {//播放全部
            setFragmentMusicList(playListBean.getMusicFileList());
        } else if (id == R.id.llPlay) {//随机播放
            mDataBinding.audioPlayerView.setSj();
            mDataBinding.audioPlayerView.startPlay();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        int id = view.getId();
        if (id == R.id.ivMusicItemEdit) {
            showEditDialog(view, musicAdapter.getItem(position).getList(),position);
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        playListBean = AppSpUtils.getPlayList().get(selPosition);
        mDataBinding.tvName.setText(playListBean.getName());
        mDataBinding.tvSize.setText(playListBean.getMusicFileList().size() + getString(R.string.music));
        if (playListBean.getMusicFileList() != null && playListBean.getMusicFileList().size() > 0) {
            long time = 0;
            for (MusicFile musicFile : playListBean.getMusicFileList()) {
                time += musicFile.getDuration();
            }

            MusicFile musicFile = playListBean.getMusicFileList().get(0);

            Bitmap albumCover = MusicScannerUtil.getAlbumArt(this, musicFile.getAlbumCover());
            Bitmap bit = MusicScannerUtil.getAlbumArt((Activity) this, musicFile.getArtistCover());

            if (albumCover != null) {
                mDataBinding.ivImg.setImageBitmap(albumCover);
            } else {
                if (bit != null) {
                    mDataBinding.ivImg.setImageBitmap(bit);
                }
            }
            mDataBinding.audioPlayerView.setPlayList(playListBean.getMusicFileList(), 0);
            listShow = MusicScanner.groupByProperty(this, playListBean.getMusicFileList());
            mDataBinding.tvTime.setText(TimeUtil.getHHmmss(time));
            musicAdapter.setList(listShow);
            mDataBinding.rvMusicList.setVisibility(View.VISIBLE);
            mDataBinding.tvMusicNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.tvTime.setText("00:00:00");
            mDataBinding.ivImg.setImageResource(R.drawable.bofangliebiao);
            mDataBinding.rvMusicList.setVisibility(View.VISIBLE);
            mDataBinding.tvMusicNoData.setVisibility(View.GONE);
        }
    }

    private void showPlaylistEditDialog(List<MusicFile> musicFile) {
        PlaylistEditDialog dialog = new PlaylistEditDialog(mContext);
        BasePopupView basePopupView = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .offsetX(0)//x轴偏移
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.ivEdit).hasShadowBg(false) // 去掉半透明背景
                .asCustom(dialog);
        dialog.setListener(new PlaylistEditDialog.Ilistener() {
            @Override
            public void clickItem(int pos) {
                switch (pos) {
                    case 0://播放
                        setFragmentMusicList(musicFile);
                        break;
                    case 1://下一首播放
                        setNextMusic(musicFile);
                        break;
                    case 2://重命名
                        showRenameDialog();
                        break;
                    case 3://删除
                        showDeleteDialog();
                        break;
                    case 4://保存为文件
                        saveToFile();
                        break;
                }
            }
        });
        basePopupView.show();
    }

    private void showEditDialog(View view, List<MusicFile> musicFile, int position) {
        MusicEditDialog dialog = new MusicEditDialog(mContext);
        BasePopupView basePopupView = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .offsetX(0)//x轴偏移
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(view).hasShadowBg(false) // 去掉半透明背景
                .asCustom(dialog);
        dialog.setListener(new MusicEditDialog.Ilistener() {
            @Override
            public void clickItem(int pos) {
                switch (pos) {
                    case 0://播放
                        setFragmentMusicList(musicFile);
                        break;
                    case 1://加入播放队列
                        SaveListUtils.saveDlList(PlaylistDetailActivity.this, musicFile);
                        break;
                    case 2://加入播放列表
                        showPlaylistDialog(musicFile);
                        break;
                    case 3://设为铃声
                        RingtoneUtil.setRingtone(mContext, musicFile.get(0).getPath(), RingtoneManager.TYPE_RINGTONE);
                        break;
                    case 4://删除
                        showDeleteMusicDialog(position);
                        break;
                }
            }
        });
        basePopupView.show();
    }

    private void showRenameDialog() {
        RenamePlaylistDialog dialog = new RenamePlaylistDialog(mContext);
        dialog.setText(playListBean.getName());
        dialog.setListener(new RenamePlaylistDialog.Ilistener() {
            @Override
            public void clickConfirm(String text) {
                playListBean.setName(text);
                List<PlayListBean> listSp = AppSpUtils.getPlayList();
                listSp.set(selPosition, playListBean);
                AppSpUtils.savePlayList(listSp);
                getData();
            }
        });
        dialog.show();
    }

    private void showPlaylistDialog(List<MusicFile> musicFile) {
        PlaylistDialog playlistDialog = new PlaylistDialog(mContext);
        playlistDialog.setMusicFileList(musicFile);
        playlistDialog.show();
    }

    private void setFragmentMusicList(List<MusicFile> listFile) {
        if (listFile != null && !listFile.isEmpty()) {
            mDataBinding.audioPlayerView.setPlayList(listFile, 0);
            mDataBinding.audioPlayerView.startPlay();
        }
    }

    public void setNextMusic(List<MusicFile> listFile) {
        if (listFile != null && listFile.size() > 1) {
            mDataBinding.audioPlayerView.setPlayList(listFile, 0);
            mDataBinding.audioPlayerView.next();
            mDataBinding.audioPlayerView.startPlay();
        }
    }

    private void showDeleteDialog() {
        DeleteDialog dialog = new DeleteDialog(mContext);
        dialog.setText(getString(R.string.playlist_delete_tip));
        dialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                List<PlayListBean> listSp = AppSpUtils.getPlayList();
                listSp.remove(selPosition);
                AppSpUtils.savePlayList(listSp);
                ToastUtils.showShort(getString(R.string.delete_suc));
                finish();
            }
        });
        dialog.show();
    }

    private void showDeleteMusicDialog(int pos) {
        DeleteDialog dialog = new DeleteDialog(mContext);
        dialog.setText(getString(R.string.playlist_music_delete_tip));
        dialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                playListBean.getMusicFileList().remove(pos);
                List<PlayListBean> listSp = AppSpUtils.getPlayList();
                listSp.set(selPosition, playListBean);
                AppSpUtils.savePlayList(listSp);
                getData();
            }
        });
        dialog.show();
    }

    private void saveToFile() {
        String savePath = PathUtils.getFilesPathExternalFirst() + Content.mySave;
        // 确保目录存在
        FileUtils.createOrExistsDir(savePath);

        // 文件名使用播放列表名称，确保不包含特殊字符
        String fileName = playListBean.getName().replaceAll("[\\/:*?\"<>|]", "_") + ".m3u";
        String filePath = savePath + "/" + fileName;

        // 构建m3u文件内容
        StringBuilder content = new StringBuilder();
        // m3u文件头
        content.append("#EXTM3U\n");

        // 添加每首歌曲的信息
        for (MusicFile musicFile : playListBean.getMusicFileList()) {
            // 添加EXTINF行，格式为#EXTINF:时长(秒),标题 - 艺术家
            long durationSeconds = musicFile.getDuration() / 1000; // 转换为秒
            String title = musicFile.getTitle();
            String artist = musicFile.getArtist();
            content.append("#EXTINF:")
                    .append(durationSeconds)
                    .append(",")
                    .append(title)
                    .append(" - ")
                    .append(artist)
                    .append("\n");
            // 添加歌曲文件路径
            content.append(musicFile.getPath()).append("\n");
        }

        // 写入文件
        boolean success = false;
        try {
            // 使用标准Java IO写入文件
            File file = new File(filePath);
            FileWriter writer = new FileWriter(file, false); // false表示覆盖模式
            writer.write(content.toString());
            writer.close();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 显示保存结果提示
        if (success) {
            ToastUtils.showShort("播放列表已保存至: " + filePath);
        } else {
            ToastUtils.showShort("保存失败，请检查存储权限");
        }
    }

    @Override
    public void onPlaybackStateChanged(boolean isPlaying) {
        if (isPlaying) {
            mDataBinding.audioPlayerView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPlaybackStateChanged(int state) {

    }

    @Override
    public void onProgressUpdated(long position, long duration) {

    }

    @Override
    public void onTrackChanged(MusicFile currentTrack) {

    }
}